<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\admin\controller\match;

use app\admin\model\User;
use app\common\controller\BackendApi;
use app\common\library\Auth;
use app\common\library\InviteCode;
use app\common\manager\LogManager;
use fast\Random;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 赛事成员管理
 *
 * @icon fa fa-circle-o
 */
class Member extends BackendApi
{

    /**
     * Member模型对象
     * @var \app\admin\model\match\Member
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\match\Member;
        $this->view->assign("isOutList", $this->model->getIsOutList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $matchId = $this->request->param("ids");
        $mid = $this->request->param("mid");
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['match','user'])
                    ->where($where)
                    ->where(function ($query) use ($mid) {
                        if ($mid){
                            return $query->where('match_id',$mid);
                        }
                    })
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {

                if ($row->out_round){
                    $row->out_round_title = \app\admin\model\match\Round::where('round_id',$row->out_round)->value('title') ?? '';
                }else{
                    $row->out_round_title = '';
                }
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assign('matchId', $matchId);
        return $this->view->fetch();
    }

    public function add(){
        $startTime = microtime(true);
        $matchId = $this->request->param('matchId');
        if (false === $this->request->isPost()) {
            $this->assign('matchId', $matchId);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            if ($this->model->where('match_id',$params['match_id'])->where('mobile',$params['mobile'])->count()){
                $this->error('当前赛事，当前手机号用户已存在');
            }
            if ($params['mobile'] && $userinfo = User::where('mobile',$params['mobile'])->find()){
                $params['user_id'] = $userinfo['id'];
            }else{
                $auth = Auth::instance();
                $auth->register($params['mobile'],Random::alnum(),'',$params['mobile']);
                $params['user_id'] = $auth->getUserId();
            }
            $inviteCode = new InviteCode();
            $invite = $inviteCode->enCode();
            $params['verify_code'] = $invite;
            $params['backend_system'] = \app\admin\model\match\Member::BACKEND_SYSTEM_YES;
            $params['create_time'] = time();
            $params['update_time'] = time();

            $result = $this->model->allowField(true)->save($params);
            $where = ['people_count'=>Db::raw('people_count > join_count')];
            if(!\app\admin\model\Match::where('m_id',$params['match_id'])->where($where)->update(['join_count'=>Db::raw('join_count + 1'),'order_count'=>Db::raw('order_count + 1'),'up_date'=>time()])){
                throw new Exception('人数超过总人数，无法添加');
            }
            Db::commit();
            $adminInfo = $this->auth->getUserInfo();
            $endTime = microtime(true);
            hook('Log',[
                'username'=>$adminInfo['username'],
                'user_id'=>$adminInfo['id'],
                'tips'=>'添加赛事成员',
                'data'=>$params,
                'match_id'=>$params['match_id'],
                'start_time'=>$startTime,
                'end_time'=>$endTime,
                'type'=>LogManager::TYPE_SERVER,
                'redirect'=>LogManager::MATCH_REDIRECT_PATH.date('Y').'/'.date('m').'/'.date('d'),
            ]);
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function edit($ids=null)
    {
        $startTime = microtime(true);
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if ($this->model->where('match_id',$params['match_id'])->where('mobile',$params['mobile'])->count()){
                $this->error('当前赛事，当前手机号用户已存在');
            }
            if ($params['mobile'] && $row->mobile != $params['mobile'] ){
                if ($userinfo = User::where('mobile',$params['mobile'])->find()){
                    $params['user_id'] = $userinfo['id'];
                }else{
                    $auth = Auth::instance();
                    $auth->register($params['mobile'],Random::alnum(),'',$params['mobile']);
                    $params['user_id'] = $auth->getUserId();
                }
            }
            $result = $row->allowField(true)->save($params);
            $adminInfo = $this->auth->getUserInfo();
            $endTime = microtime(true);
            hook('Log',[
                'username'=>$adminInfo['username'],
                'user_id'=>$adminInfo['id'],
                'tips'=>'编辑赛事成员',
                'data'=>$params,
                'match_id'=>$row->match_id,
                'start_time'=>$startTime,
                'end_time'=>$endTime,
                'type'=>LogManager::TYPE_SERVER,
                'redirect'=>LogManager::MATCH_REDIRECT_PATH.date('Y').'/'.date('m').'/'.date('d'),
            ]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    public function del($ids=null)
    {
        $startTime = microtime(true);
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        $row = $this->model->get($ids);
        if (!$row){
            $this->error(__('No Results were found'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                if ($item->order_id  > 0 ){
                    throw new Exception('当前删除记录中有支付订单，无法删除');
                }
                $count += $item->delete();
                \app\admin\model\Match::where('m_id',$row->match_id)->where('join_count','>',0)->where('order_count','>',0)->update(['join_count'=>Db::raw('join_count - 1'),'order_count'=>Db::raw('order_count - 1'),'up_date'=>time()]);
            }
            $adminInfo = $this->auth->getUserInfo();
            $endTime = microtime(true);
            hook('Log',[
                'username'=>$adminInfo['username'],
                'user_id'=>$adminInfo['id'],
                'tips'=>'删除赛事成员',
                'data'=>$this->request->post(),
                'match_id'=>$row->match_id,
                'start_time'=>$startTime,
                'end_time'=>$endTime,
                'type'=>LogManager::TYPE_SERVER,
                'redirect'=>LogManager::MATCH_REDIRECT_PATH.date('Y').'/'.date('m').'/'.date('d'),
            ]);
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

}
